//
//  WedingRegistrationViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/11/16.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "LSTPopView.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import "BRAddressPickerView.h"

#import "POIAnnotation.h"
#import "WedingRegistrationCell.h"

#import "TT_GDMapManager.h"
#import "WedingRegistrationHeadView.h"
#import "TT_GDAnnotationView.h"


#import "WedingRegistrationViewController.h"

@interface WedingRegistrationViewController ()<
UITableViewDelegate,
UITableViewDataSource,
MAMapViewDelegate,
AMapSearchDelegate,
AMapLocationManagerDelegate
>

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, strong) AMapSearchAPI *searchApi;
@property (nonatomic, copy) NSString *searchCity;

@property (nonatomic, strong) LSTPopView *popView;

@property (nonatomic, strong) NSMutableArray <POIAnnotation *>*poiAnnotations;

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) WedingRegistrationHeadView *headView;

@property(strong, nonatomic) CLLocation *currentLocation;
//进入控制器时间
@property(nonatomic,strong)NSString *inTime;
@end

@implementation WedingRegistrationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    self.inTime = [NSString stringWithFormat:@"%0.0f",[Utilities getCurrentTimestamp]];
}
- (void)dealloc
{
    NSLog(@"WedingRegistrationViewController ---dealloc");
    [[StatisticManager shareManager]insertBrowseUserActiveQuantityWithToolType:@"6" WithInTime:self.inTime];
}
- (void)initView {
    self.title = @"婚姻登记处";
    
    [self.view addSubview:self.mapView];
    [self.view addSubview:self.tableview];
    self.headView = [[NSBundle mainBundle] loadNibNamed:@"WedingRegistrationHeadView"owner:nil options:nil].firstObject;
    [self.view addSubview:self.headView];
    
    [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(TTScreenWidth- 50);
    }];
    
    [self.headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        //make.top.mas_equalTo(self.mapView.mas_bottom);
        make.top.mas_equalTo(TTScreenWidth- 50);
        make.height.mas_equalTo(50);
    }];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(self.headView.mas_bottom);
    }];
    
    [self configLocationManager];
    
    if ([TTUserModel sharedObject].cityName.length > 0) {
        self.searchCity = [TTUserModel sharedObject].cityName;
    } else {
        self.searchCity = @"合肥市";
    }
    [self searchData];
    
    [self initViewAction];
}

- (void)searchData {
    
    [self searchActionWithCityName:self.searchCity];
    self.headView.cityLab.text = [NSString stringWithFormat:@"当前城市：%@",self.searchCity] ;
}

- (void)initViewAction {
    
    [self.headView.changeCityBtn addTarget:self action:@selector(changeCity) forControlEvents:UIControlEventTouchUpInside];
}

- (void)changeCity {
    
    WEAKSELF
    [BRAddressPickerView showAddressPickerWithMode:BRAddressPickerModeCity selectIndexs:@[@(11),@(0),@(3)] isAutoSelect:NO resultBlock:^(BRProvinceModel * _Nullable province, BRCityModel * _Nullable city, BRAreaModel * _Nullable area) {
        
        if (city.name.length > 0) {
            weakSelf.searchCity = city.name;
        } else {
            weakSelf.searchCity = province.name;
        }
        [weakSelf searchData];
    }];
    
}

- (void)configLocationManager {

    WK(weakSelf)
    [[TT_GDMapManager shareMap] location_getCurrentLocationComption:^(CLLocation * _Nonnull location, BOOL success, NSError * _Nonnull error) {
        weakSelf.currentLocation = location;
    }];
}


//根据城市名称搜索民政局
- (void)searchActionWithCityName:(NSString *)cityName {
    
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
    request.keywords            = @"民政局";
    request.city                = cityName;
    request.types               = @"";
    //request.requireExtension    = YES;
    /*  搜索SDK 3.2.0 中新增加的功能，只搜索本城市的POI。*/
    request.cityLimit           = YES;
    //request.requireSubPOIs      = YES;
    
    WK(weakSelf)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.searchApi AMapPOIKeywordsSearch:request];
    });
    
}

/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    WK(weakSelf)
    if (response.pois.count == 0) {

        [SVProgressHUD showErrorWithStatus:@"当前城市无民政局"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    //解析response获取POI信息，具体解析见 Demo
    self.poiAnnotations = @[].mutableCopy;
    self.poiAnnotations = [NSMutableArray arrayWithCapacity:response.pois.count];
    
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
        [weakSelf.poiAnnotations addObject:[[POIAnnotation alloc] initWithPOI:obj]];
    }];
    
    /* 将结果以annotation的形式加载到地图上. */
    [self.mapView addAnnotations:self.poiAnnotations];
    
    /* 如果只有一个结果，设置其为中心点. */
    if (self.poiAnnotations.count == 1) {
        [self.mapView setCenterCoordinate:self.poiAnnotations[0].coordinate];
    }
    /* 如果有多个结果, 设置地图使所有的annotation都可见. */
    else {
        [self.mapView showAnnotations:self.poiAnnotations animated:NO];
    }
    [self.tableview reloadData];
    
}

#pragma mark ----- Location  Delegate -----
#pragma mark 定位结果
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location {
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    self.currentLocation = location;
}



- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode {
    NSLog(@"reGeocode ------ location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    self.currentLocation = location;

}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return self.dataArray.count;
    return 1;

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.poiAnnotations.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WedingRegistrationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WedingRegistrationCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillCellWithModel:self.poiAnnotations[indexPath.row] AndLocation:self.currentLocation];
    
    WEAKSELF
    cell.WedingRegistrationCellBlock = ^(WedingRegistrationCellActionType type) {
        
        switch (type) {
            case WedingRegistrationCellActionType_navi:{
                
                [Utilities callMapWithLat:weakSelf.poiAnnotations[indexPath.row].coordinate.latitude lng:weakSelf.poiAnnotations[indexPath.row].coordinate.longitude AndAddress:weakSelf.poiAnnotations[indexPath.row].poi.name];

            } break;
            case WedingRegistrationCellActionType_call:{
                
                NSString *calls = weakSelf.poiAnnotations[indexPath.row].poi.tel;
                NSArray  *callArray = [calls componentsSeparatedByString:@";"];

                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
                
                
                for (int i = 0; i < callArray.count; i++) {
                    
                    NSString *itemTitle = callArray[i];
                    UIAlertAction *liveAction = [UIAlertAction actionWithTitle:itemTitle
                                                             style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction *action) {
                        [Utilities callPhone:itemTitle];
                    }];
                    
                    if (itemTitle.length > 0) {
                        [alertController addAction:liveAction];
                    }
                }

                
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消"
                                                       style:UIAlertActionStyleCancel
                                                     handler:^(UIAlertAction *action) {

                }];
                [alertController addAction:cancleAction];
                
                [alertController setModalPresentationStyle:UIModalPresentationPopover];
                [weakSelf presentViewController:alertController animated:YES completion:nil];
                
            } break;
            default:
                break;
        }
        
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //设置地图缩放比例，即显示区域
    [_mapView setZoomLevel:15.1 animated:YES];
    _mapView.delegate = self;
    //设置定位精度
    _mapView.desiredAccuracy = kCLLocationAccuracyBest;
    //设置定位距离
    _mapView.distanceFilter = 5.0f;
    self.mapView.centerCoordinate = self.poiAnnotations[indexPath.row].coordinate;
}

- (CLLocation *)currentLocation {
    if (!_currentLocation) {
        _currentLocation = [[CLLocation alloc] init];
    }
    return _currentLocation;
}

- (MAMapView *)mapView {
    if (!_mapView) {
        _mapView = [[MAMapView alloc] init];
        ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
        
        _mapView.showsUserLocation = YES;
        _mapView.userTrackingMode = MAUserTrackingModeFollow;
        //设置地图缩放比例，即显示区域
        [_mapView setZoomLevel:15.1 animated:YES];
        _mapView.delegate = self;
        //设置定位精度
        _mapView.desiredAccuracy = kCLLocationAccuracyBest;
        //设置定位距离
        _mapView.distanceFilter = 5.0f;
    }
    return _mapView;;
}

- (AMapSearchAPI *)searchApi {
    if (!_searchApi) {
        _searchApi = [[AMapSearchAPI alloc] init];
        _searchApi.delegate = self;
    }
    return _searchApi;;
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"WedingRegistrationCell" bundle:nil] forCellReuseIdentifier:@"WedingRegistrationCellID"];
    }
    return _tableview;
} 

@end
